package org.beanstech.dao;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.beanstech.dao.service.AbstractDao;
import org.beanstech.persistence.Tbluser;
import org.beanstech.util.StaticHibernateUtil;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

public class UserDao extends AbstractDao {

	public int insertUser(Tbluser user){
		
		int userid = 0;
		try{
			user.setCreatedon(new Date());
			
			userid = insert(user);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return userid;
	}
	
	public Tbluser getUserById(int userid){
		Tbluser user = null;
		
		user = (Tbluser)getObject(Tbluser.class, userid);
		return user;
	}
	
	public Tbluser getLoginDetails(Tbluser user){
		boolean loggedin = false;
		Tbluser myreturnuser=null;
		try{
		
			StaticHibernateUtil.initialize();
			Session session = StaticHibernateUtil.getSessionTL();
			StaticHibernateUtil.startTransaction();
			Criteria aUser = session.createCriteria(Tbluser.class).add(Restrictions.or(Restrictions.eq("emailid", user.getEmailid()), Restrictions.eq("password", user.getPassword())));
			
			if(aUser != null && aUser.list().size()==1){
				loggedin=  true;
				for(Iterator i = aUser.list().iterator(); i.hasNext();){
					Tbluser loguser = (Tbluser)i.next();
					loguser.setLastloggedin(new Date());
					myreturnuser = loguser;
				}
			}
			else
				loggedin =  false;
			
			StaticHibernateUtil.commitTransaction();
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return myreturnuser;
	}
	
	
}
